<?php

namespace App\Library;

use App\Models\Content\Attachment;
use App\Models\Logs\ActivityLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class AttachmentTools
{
     public const IMAGE_SIZE = 2048;
     public const IMAGE_TYPE = ["jpg", "jpeg", "png", "gif", "webp", "avif"];
     public const FILE_SIZE = 5120;
     public const FILE_TYPE = ['mp3', 'mp4', 'mov'];

    /**
     * @param string $storage
     * @return \Illuminate\Contracts\Filesystem\Filesystem|mixed
     */
    public static function getDisk(string $storage = 'local')
    {
        switch ($storage) {
            case 'kodo':
                $disk = Storage::disk('qiniu');
                break;
            case 'oss':
                $disk = Storage::disk('oss');
                break;
            case 'cos':
                $disk = Storage::disk('cos');
                break;
            default:
                $disk = Storage::disk('public');
        }
        return $disk;
    }

    /**
     * @param string $path
     * @param string $storage
     * @return bool
     */
    public static function deleteFile(string $path, string $storage = 'local'): bool
    {
        if (empty($path)) {
            return false;
        }
        $disk = self::getDisk($storage);
        if (!$disk->exists($path)) {
            return false;
        }
        return $disk->delete($path);
    }

    /**
     * @param array $fileData
     * @return mixed|null
     */
    public static function createAttachment(array $fileData)
    {
        if (!empty($fileData)) {
            DB::beginTransaction();
            try {
                $model = Attachment::query()->create($fileData);
                ActivityLog::CreateSyslog('添加附件', $model);
                DB::commit();
                return $model;
            } catch (\Exception $e) {
                DB::rollBack();
                report($e);
            }
        }
        return null;
    }
}
